package id.ac.amikom.libs;

import java.net.URI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.util.Log;

public class AdemServiceHelper {

	private URI uri = URI.create("http://www.amikom.ac.id/index.php/service/");
	private XMLRPCClient client = new XMLRPCClient(uri);

	private URI uris = URI.create("http://www.amikomsocial.com/service/");
	private XMLRPCClient clients = new XMLRPCClient(uris);

	private AdemDBHelper db = null;
	private SharedPreferences pref;
	private int infoAdd;
	private int newsAdd;
	private int materiAdd;
	private int infoId;
	private int newsId;
	private String fotoUrl;
	private String materiDate;

	public AdemServiceHelper(Context context) {
		db = new AdemDBHelper(context);
		infoId = db.getLastInfoId();
		newsId = db.getLastNewsId();
		materiDate = db.getLastMateri();

		db.close();
		pref = PreferenceManager.getDefaultSharedPreferences(context);
	}

	public boolean checkInfoService() {

		Cursor c = db.getInfo();
		int count = c.getCount();
		int rows = Integer.parseInt(pref.getString("id_rows", "10"));
		int sid = 0;

		try {
			String ssid = (String) client.call("lastinfo");
			JSONArray jsArray = new JSONArray(ssid);

			for (int i = 0; i < jsArray.length(); i++) {
				JSONObject json = jsArray.getJSONObject(i);
				sid = Integer.parseInt(json.getString("agenda_id"));

			}

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		c.close();
		db.close();

		Log.i("info", sid + " " + infoId);
		if (count == 0 || sid > infoId || count != rows) {

			return true;
		} else {
			return false;
		}

	}

	public boolean checkNewsService() {

		Cursor c = db.getNews();
		int count = c.getCount();
		int rows = Integer.parseInt(pref.getString("id_rows", "10"));
		int sid = 0;

		try {
			String ssid = (String) client.call("lastnews");
			JSONArray jsArray = new JSONArray(ssid);

			for (int i = 0; i < jsArray.length(); i++) {
				JSONObject json = jsArray.getJSONObject(i);
				sid = Integer.parseInt(json.getString("berita_id"));

			}

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		c.close();
		db.close();

		Log.i("news", sid + " " + newsId);
		if (count == 0 || sid > newsId || count != rows) {

			return true;
		} else {
			return false;
		}
	}

	public boolean checkCalendarService() {

		Cursor c = db.getCalendar();
		int count = c.getCount();
		int id = db.getCalendarId();
		int pid = 0;

		try {
			String str = (String) client.call("jdwupdate");
			pid = Integer.parseInt(str);

		} catch (XMLRPCException e) {
			e.printStackTrace();
			return false;
		}

		c.close();
		db.close();

		if (count == 0 || pid > id)
			return true;
		else
			return false;
	}

	public boolean checkMateriService() {

		Cursor c = db.getMateri();
		int count = c.getCount();
		int rows = Integer.parseInt(pref.getString("id_rows", "10"));
		String strDate = "";

		try {
			String str = (String) client.call("getmateri", "1");
			JSONArray jsArray = new JSONArray(str);

			for (int i = 0; i < jsArray.length(); i++) {
				JSONObject json = jsArray.getJSONObject(i);

				strDate = json.getString("tgl");

			}

		} catch (XMLRPCException e) {
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		c.close();
		db.close();

		Log.i("materi", strDate + " " + materiDate);

		if (strDate.equals(""))
			return false;

		DateParse mDate = new DateParse(materiDate.trim());
		long materiDate = mDate.parse();

		DateParse sDate = new DateParse(strDate.trim());
		long serverDate = sDate.parse();

		Log.i("long-date", serverDate + " " + materiDate);

		if (count == 0 || serverDate > materiDate || count != rows) {
			return true;
		} else {
			return false;
		}

	}

	public boolean getInfoService() {
		try {

			String text = (String) client.call("getinfo",
					pref.getString("id_rows", "10"));
			JSONArray jsonArray = new JSONArray(text);
			infoAdd = 0;

			if (jsonArray.length() > 0)
				db.deleteInfo();

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = jsonArray.getJSONObject(i);

				int sid = Integer.parseInt(json.getString("agenda_id"));
				if (sid > infoId)
					infoAdd++;

				db.insertInfo(json.getString("agenda_id"),
						json.getString("agenda_jdl"),
						json.getString("TGL_MULAI_PUBLIKASI"),
						json.getString("TGL_END"),
						json.getString("agenda_detail"));

			}
			
			db.close();

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean getNewsService() {
		try {
			String text = (String) client.call("getnews",
					pref.getString("id_rows", "10"));
			JSONArray jsonArray = new JSONArray(text);
			newsAdd = 0;

			if (jsonArray.length() > 0)
				db.deleteNews();

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = jsonArray.getJSONObject(i);

				int sid = Integer.parseInt(json.getString("berita_id"));
				if (sid > newsId)
					newsAdd++;

				db.insertNews(json.getString("berita_id"),
						json.getString("berita_jdl"),
						json.getString("berita_tgl"),
						json.getString("permalink"),
						json.getString("berita_detail"));

			}
			
			db.close();

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean getMateriService() {
		try {
			String text = (String) client.call("getmateri",
					pref.getString("id_rows", "10"));
			JSONArray jsonArray = new JSONArray(text);
			materiAdd = 0;

			if (jsonArray.length() > 0)
				db.deleteMateri();

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = jsonArray.getJSONObject(i);

				long sid = new DateParse(json.getString("tgl").trim()).parse();

				if (sid > (new DateParse(materiDate).parse()))
					materiAdd++;

				db.insertMateri(
						json.getString("nama").trim(),
						json.getString("mkl").trim() + "("
								+ json.getString("kode").trim() + ")", json
								.getString("judul").trim(),
						json.getString("namafile").trim(), json
								.getString("tgl"), json.getString("sinopsis"),
						json.getString("fsize"));

			}
			
			db.close();

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean getShoutService() {

		String text;
		try {

			int lastId = db.getLastShoutId();

			// Log.i("last ---- > ", ""+lastId);

			text = (String) clients.call("getmsg", "" + lastId, "50");
			JSONArray jsonArray = new JSONArray(text);

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = jsonArray.getJSONObject(i);

				db.insertShout(json.getString("id_msg"), json.getString("nid"),
						json.getString("fullname"), json.getString("alias"),
						json.getString("msg"), json.getString("thumb"),
						json.getString("status"), json.getString("time"),
						json.getString("via"));
				
				db.close();

			}

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		
		return true;
	}

	public boolean postShoutService(String uid, String msg) {
		try {

			clients.call("addmsg", uid, msg, "Android");

		} catch (XMLRPCException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public String editUser(String uid, String usr) {

		String out = "";
		try {

			String service = (String) clients.call("edituser", uid, usr);
			JSONArray jsonArray = new JSONArray(service);
			JSONObject json = jsonArray.getJSONObject(0);

			out = json.getString("msg");

		} catch (XMLRPCException e) {
			out = "No Internet Connection";
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return out;
	}

	public void updateCalendarId() {
		try {
			String text = (String) client.call("jdwupdate");
			int id = Integer.parseInt(text);
			db.updateCalendarId(id);

		} catch (XMLRPCException e) {
			e.printStackTrace();
		}
	}

	public boolean getCalendarService() {

		Cursor c = db.getLogin();
		String usr = "";
		if (c.moveToFirst()) {
			do {
				usr = c.getString(c.getColumnIndex("usr"));
			} while (c.moveToNext());
		}

		try {
			String text = "";
			if (db.isMhs())
				text = (String) client.call("jdwkuliah", usr);
			else
				text = (String) client.call("jdwdosen", usr);

			JSONArray jsonArray = new JSONArray(text);
			if (jsonArray.length() > 0) {

				db.deleteCalendar();

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);

					String[] jam = json.getString("jam").split("\\-+");

					if (db.isMhs()) {
						db.insertCalendar(json.getString("hari").trim() + " - "
								+ json.getString("kuliah"),
								json.getString("fdate") + " " + jam[0],
								json.getString("edate") + " " + jam[1],
								"STMIK Amikom - " + json.getString("ruang"),
								json.getString("dosen"),
								Integer.parseInt(json.getString("weekly")));
					} else {
						db.insertCalendar(json.getString("hari").trim() + " - "
								+ json.getString("mkul"),
								json.getString("fdate") + " " + jam[0],
								json.getString("edate") + " " + jam[1],
								"STMIK Amikom - " + json.getString("ruang"),
								json.getString("kelasgab"),
								Integer.parseInt(json.getString("weekly")));
					}

				}

				updateCalendarId();
			}

			getAkademikCalendarService();

			c.close();
			db.close();

		} catch (XMLRPCException ex) {
			getAkademikCalendarService();
			ex.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean getAkademikCalendarService() {
		try {
			String text = (String) client.call("getcalendar");
			JSONArray jsonArray = new JSONArray(text);

			if (jsonArray.length() > 0) {

				db.deleteAkademikCalendar();

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);

					db.insertCalendar(json.getString("detail"),
							json.getString("start"), json.getString("finish"),
							"Amikom - Amikom Calendar",
							json.getString("fdate"),
							Integer.parseInt(json.getString("weekly")));
				}

				updateCalendarId();
			}

			db.close();

		} catch (XMLRPCException er) {
			er.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean login(String id, String pwd) {

		try {
			String text = (String) client.call("login", id, pwd);
			JSONArray jsonArray = new JSONArray("[" + text + "]");
			JSONObject json = jsonArray.getJSONObject(0);

			String sts = json.getString("status");
			if (sts.equals("1")) {

				int alumni = Integer.parseInt(json.getString("alumni"));
				int status = (alumni == 1) ? 3 : 1;
				fotoUrl = json.getString("foto");

				db.insertLogin(id, status, json.getString("name"));
				db.close();				

				return true;

			} else {
				String txt = (String) client.call("logindosen", id, pwd);
				JSONArray jsArray = new JSONArray("[" + txt + "]");
				JSONObject js = jsArray.getJSONObject(0);

				String ists = js.getString("status");
				if (ists.equals("1")) {
					fotoUrl = js.getString("foto");
					
					db.insertLogin(id, 2, js.getString("name"));
					db.close();										

					return true;

				} else {
					return false;

				}
			}

		} catch (XMLRPCException e) {
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}

	}

	public void updateActivity(String loc, double lat, double lon) {

		Cursor c = db.getLogin();
		String usr = null;

		if (c.moveToFirst()) {
			do {
				usr = c.getString(c.getColumnIndex("usr"));
			} while (c.moveToNext());
		}

		String device = android.os.Build.MODEL;
		String ipaddr = new AdemInet().getLocalIpAddress();

		try {
			if (c.getCount() > 0)
				clients.call("addactivity", usr, loc, ipaddr, device, lat, lon);

		} catch (XMLRPCException e) {
			e.printStackTrace();
		}

		c.close();
		db.close();
	}

	public JSONArray getUserList(String id) {
		String text = null;
		JSONArray json = null;
		try {
			text = (String) clients.call("userlist", id);
			json = new JSONArray(text);
			
		} catch (XMLRPCException e) {
			e.printStackTrace();
		} catch (JSONException e) {			
			e.printStackTrace();
		}
		
		return json;
	}
	
	public JSONArray getUserStats() {
		String text = null;
		JSONArray json = null;
		try {
			text  = (String) clients.call("userstats");
			json = new JSONArray(text);
			
		} catch (XMLRPCException e) {
			e.printStackTrace();
		} catch (JSONException e) {			
			e.printStackTrace();
		}
		
		return json;
	}
	
	public JSONArray getDetailMateri(String key){
		String text = null;
		JSONArray json = null;
		try {
			text = (String) client.call("getdetailmateri", key);
			json = new JSONArray("[" + text + "]");
			
		} catch (XMLRPCException e) {
			e.printStackTrace();
		} catch (JSONException e) {			
			e.printStackTrace();
		}
		
		return json;
	}
	
	public JSONArray getMateri(String mode, String param){
		String text = null;
		JSONArray json = null;
		try {
			
			if (mode.equals("mkl"))
				text = (String) client.call("getmaterisubj", param);
			else
				text = (String) client.call("getmateridosen", param);
			
			json = new JSONArray(text);
			
		} catch (XMLRPCException e) {
			e.printStackTrace();
		} catch (JSONException e) {			
			e.printStackTrace();
		}
		
		return json;
	}
	
	public JSONArray getUser(String id){
		
		JSONArray json = null;
		try {
						
			String text = (String) clients.call("getuser", id);
			
			json = new JSONArray(text);
			
		} catch (XMLRPCException e) {
			e.printStackTrace();
		} catch (JSONException e) {			
			e.printStackTrace();
		}
		
		return json;
	}

	public int getInfoAdd() {
		return infoAdd;
	}

	public int getNewsAdd() {
		return newsAdd;
	}

	public int getMateriAdd() {
		return materiAdd;
	}

	public String getFotoUrl() {
		return fotoUrl;
	}

}
